package cc.ifok.kit;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

public final class Message implements Serializable {
    private static final long serialVersionUID = 5037353427216308801L;
    // sid=通道ID   cmd=操作指令    val=VALUE值
    private static final String SID = "sid", CMD = "cmd", VAL = "val", EQ = "→", DH = "⎥";
    public static final BlockingQueue<Message> RPS = new ArrayBlockingQueue<>(1023);
    public static final BlockingQueue<Message> LPS = new LinkedBlockingQueue<>();

    public static boolean working() {
        return RPS.size() != RPS.remainingCapacity();
    }
    public static Message rps() {
        try {
            return RPS.take();
        } catch (Throwable e) {
            e.printStackTrace();
            return new Message(Strings.EMPTY);
        }
    }
    public static Message lps() {
        try {
            return LPS.take();
        } catch (Throwable e) {
            e.printStackTrace();
            return new Message(Strings.EMPTY);
        }
    }

    private final Map<String, String> mvs = new ConcurrentHashMap<>();
    public Message(String sid, Command cmd, String val) {
        mvs.put(CMD, Strings.trim(cmd.name()));
        mvs.put(SID, Strings.trim(sid));
        mvs.put(VAL, Strings.trim(val));
    }
    public Message(String rps) {
        for (String sss : Strings.trim(rps).split(DH)) {
            String[] ss = Strings.trim(sss).split(EQ);
            if (ss.length == 2) {
                mvs.put(Strings.trim(ss[0]), Strings.trim(ss[1]));
            }
        }
    }

    public String sid() {
        return Strings.trim(mvs.get(SID));
    }

    public String cmd() {
        return Strings.trim(mvs.get(CMD));
    }

    public String val() {
        return Strings.trim(mvs.get(VAL));
    }

    public String stringify() {
        return String.join(DH, String.join(EQ, SID, sid()), String.join(EQ, CMD, cmd()), String.join(EQ, VAL, val()));
    }
}
